package com.igeek.boot.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Random;

/**
 * @Author fengqq
 * @Description TODO
 * @Date 2024/9/5  11:26
 */
@Service
@Slf4j
public class UVService {

    private static final String IP_KEY = "taobao.ip";

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    //开启多线程 初始化前执行
    //@PostConstruct
    public void  createUser(){
        Random random = new Random();
        for (int i = 0; i < 3; i++) {
            new Thread(()->{
                for (int j = 0; j < 50; j++) {
                    //组装IP xxx.xxx.xxx.xxx
                    String ip = random.nextInt(256) + "." + random.nextInt(256) + "." + random.nextInt(256) + "." + random.nextInt(256);
                    //将ip存储到redis中HyperLogLog
                    Long count = redisTemplate.opsForHyperLogLog().add(IP_KEY, ip);
                    log.info("{},{}访问了首页",Thread.currentThread().getName(),ip);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            },"线程"+i).start();
        }
    }



    //统计UV量
    public Long count() {
        Long count = redisTemplate.opsForHyperLogLog().size(IP_KEY);
        return count;
    }
}
